package cn.tedu.boot02.controller;

import cn.tedu.boot02.entity.User;
import cn.tedu.boot02.utils.DBUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@Controller
public class UserController {
    @RequestMapping("/reg")
    @ResponseBody
    public String reg(User user){
        //soutp 将参数列表中的参数在控制台输出, 用于打桩
        System.out.println("user = " + user);
        //获取数据库连接
        try (Connection conn = DBUtils.getConn()){
            String sql = "insert into user values(null,?,?,?)";
            //创建执行SQL语句的对象
            PreparedStatement ps = conn.prepareStatement(sql);
            //替换SQL语句中的?
            ps.setString(1,user.getUsername());
            ps.setString(2,user.getPassword());
            ps.setString(3,user.getNickname());
            ps.executeUpdate();//执行插入数据的SQL语句
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return "注册成功!";
    }

    @RequestMapping("/login")
    @ResponseBody
    public String login(User user){
        System.out.println("user = " + user);
        try (Connection conn = DBUtils.getConn()){
            String sql = "select password from user where username=?";
            //创建执行SQL语句的对象
            PreparedStatement ps = conn.prepareStatement(sql);
            //把用户输入的用户名替换掉?
            ps.setString(1,user.getUsername());
            //执行查询
            ResultSet rs = ps.executeQuery();
            //判断是否查询到了数据
            if (rs.next()){//满足条件说明查询到了数据 代表用户名存在
                //判断查询到的密码(rs.getString(1))和
                // 用户输入的密码(user.getPassword())是否一致
                if (rs.getString(1).equals(user.getPassword())){
                    return "登录成功!";
                }
                return "密码错误!";
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return "用户名不存在!";
    }

}
